import { Input } from "antd";
import PropTypes from "prop-types";
const InputDoubleComponent = (props) => {
  const fixed = props.fixed || 2;

  const onChange = (e) => {
    props.onChange && props.onChange(e);
  };

  const onInput = (e) => {
    const str_map = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
    const { data: inputValue } = e.nativeEvent;

    const value = e.target.value;
    if (inputValue === "." && value.length === 1) {
      e.target.value = "0.";
    } else if (inputValue === "." && value.split(".").length <= 2) {
      e.target.value = value;
    } else if (inputValue && str_map[inputValue] === undefined) {
      e.target.value = e.target.value.slice(0, -1);
    }
    const fixedLength = value.split(".")[1]?.length || 0;
    if (fixedLength > fixed) {
      e.target.value = value.slice(0, -1);
    }
    props.onInput && props.onInput(e);
  };

  const onBlur = (e) => {
    const value = e.target.value || -1;
    const minValue = props.min || 0;
    const maxValue = props.max || undefined;

    if (Number(value) < minValue) {
      e.target.value = minValue;
      onChange(e);
    } else if (maxValue && Number(value) > maxValue) {
      e.target.value = maxValue;
      onChange(e);
    }

    props.onBlur && props.onBlur(e);
  };

  const onKeyDown = (e) => {
    if (e.key === "ArrowUp") {
      e.target.value = Number(e.target.value) + 1;
      e.target.blur();
      setTimeout(() => e.target.focus(), 0.01);
      props.onChange && props.onChange(e);
    }

    const minValue = props.min || 0;

    if (e.key === "ArrowDown" && Number(e.target.value) > minValue) {
      e.target.value = Number(e.target.value) - 1;
      props.onChange && props.onChange(e);
    }
    props.onKeyDown && props.onKeyDown(e);
  };

  return <Input {...props} onChange={onChange} onInput={onInput} onKeyDown={onKeyDown} onBlur={onBlur} />;
};
InputDoubleComponent.propTypes = {
  fixed: PropTypes.number,
  min: PropTypes.number,
  max: PropTypes.number,
  onChange: PropTypes.func,
  onInput: PropTypes.func,
  onBlur: PropTypes.func,
  onKeyDown: PropTypes.func,
};

export default InputDoubleComponent;
